package com.pig4cloud.pig.demo.Controller;

import com.alibaba.fastjson.JSON;
import com.pig4cloud.pig.common.security.annotation.Inner;
import com.pig4cloud.pig.demo.Service.UserService;
import com.pig4cloud.pig.demo.feign.Entity.User;
import io.itit.itf.okhttp.FastHttpClient;
import io.itit.itf.okhttp.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@Inner
@Controller
@RequestMapping("/github")
public class GithubLogin {
    @Value("${github.ClientID}")
    private String clientId;

    @Value("${github.ClientSecret}")
    private String clientSecret;

    @Autowired
    private UserService userService;

    @GetMapping("/callback")
    public String callback(String code) throws Exception {
        String accessToken = "https://github.com/login/oauth/access_token";

        //FastHttpClient使用方法
        //https://gitee.com/icecooly/FastHttpClient/blob/master/test/io/itit/itf/okhttp/test/HttpClientTestCase.java
        Response response = FastHttpClient.post()
                .url(accessToken)
                .addParams("client_id", clientId)
                .addParams("client_secret", clientSecret)
                .addParams("code", code)
                .build()
                .execute();

        //获取下列String中access_token对应的值
        //access_token=5f460c1c0e81c74c04032129854e5eb8c8154465&scope=user&token_type=bearer
        String access_token = response.string().split("&")[0].split("=")[1];

        String authorization = "token " + access_token;

        //获取API
        Response execute = FastHttpClient.get()
                .url("https://api.github.com/user")
                .addHeader("Authorization", authorization)
                .build()
                .execute();

        String result = execute.string();

        //将json转化为map,方便获取
        Map<String, String> parse = (Map<String, String>) JSON.parse(result);

        //没有判断表中是否存在该用户直接添加
        User user = new User();
        user.setUsername(parse.get("login"));
        user.setPassword(parse.get("login"));
        user.setAvatar(parse.get("avatar_url"));
        user.setAccount(parse.get("login"));
        if (parse.get("name") != null)
            user.setNickName(parse.get("name"));
        if (parse.get("email") != null)
            user.setEmail(parse.get("email"));

        userService.insert(user);

        return "redirect:http://localhost:8989/#/all";
    }

    @GetMapping("/login")
    @ResponseBody
    public String getCode() throws Exception {
        String url = "https://github.com/login/oauth/authorize?client_id=" + clientId + "&scope=user";

        return url;
    }
}
